﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Threading;
using DiamondDash.Utils;
using DiamondDash.Core;
using System.Windows.Media.Animation;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;

namespace DiamondDash.Pages
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static GamePage Instance = null;

        /// <summary>
        /// 游戏状态 0-初始化 1-游戏中 2-暂停 3-结束
        /// </summary>
        public int gameStatus = 0;
        DispatcherTimer gameSecondTimer;
        DispatcherTimer toolGenTimer;
        int leftSeconds = 60;
        int diamondCompleteCount = 0;
        int diamondCompleteBase = 40;
        int currentScore = 0;
        int totalToolCountInRound = 0;
        bool isUseBomb = false;
        bool isUseColor = false;
        bool isUseTimer = false;
        int gameTotleSeconds = 1;

        DispatcherTimer mokaAdsSwitchTimer;
        int currentMokaAdIndex = 0;
        int totalMokaAdCount = 3;

        Random r = new Random(DateTime.Now.Millisecond);
        bool usemoka = true;

        public GamePage()
        {
            InitializeComponent();
            Instance = this;
            //初始化定时器
            gameSecondTimer = new DispatcherTimer();
            gameSecondTimer.Interval = TimeSpan.FromSeconds(1);
            gameSecondTimer.Tick += gameSecondTimer_Tick;

            //道具生成定时器
            toolGenTimer = new DispatcherTimer();
            toolGenTimer.Interval = TimeSpan.FromSeconds(1);
            toolGenTimer.Tick += toolGenTimer_Tick;

            this.StoryboardGO.Completed += StoryboardGO_Completed;
            this.StoryboardGO.BeginTime = TimeSpan.FromMilliseconds(500);
            this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(500);
            this.StoryboardTimesup.Completed += StoryboardTimesup_Completed;
            this.gameCanvas.IsHitTestVisible = false;

            //魔卡广告切换Timer
            mokaAdsSwitchTimer = new DispatcherTimer();

            //获取间隔参数
            int intervalSec = 30;
            string secStr = UmengSDK.UmengAnalytics.GetOnlineParam("moka_banner_switch_sec");
            if (!int.TryParse(secStr, out intervalSec))
            {
                intervalSec = 30;
            }

            mokaAdsSwitchTimer.Interval = TimeSpan.FromSeconds(intervalSec);
            mokaAdsSwitchTimer.Tick += mokaAdsSwitchTimer_Tick;
            mokaAdsSwitchTimer.Start();

            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if (usemokaStr == "1" || usemokaStr == "2")
            {
                usemoka = true;
                if (StageManager.Instance.TurnMoka)
                {
                    //移动moka到最前面，而且不显示亿动
                    LayoutRoot.Children.Remove(imgBanner);
                    LayoutRoot.Children.Add(imgBanner);
                }
                StageManager.Instance.TurnMoka = !StageManager.Instance.TurnMoka;
                currentMokaAdIndex = 0;
                switchMokaAdImage();
            }
            else if (usemokaStr == "0" || usemokaStr == "3")
            {
                this.imgBanner.Visibility = System.Windows.Visibility.Collapsed;
                usemoka = false;
            }
            else
            {
                usemoka = false;
            }
        }


        /// <summary>
        /// 更新魔卡广告的banner
        /// </summary>
        private void switchMokaAdImage()
        {
            BitmapImage bitmap = new BitmapImage(new Uri(@"\Images\banner" + (currentMokaAdIndex + 1).ToString() + ".jpg", UriKind.RelativeOrAbsolute));
            this.imgBanner.Source = bitmap;
        }

        void mokaAdsSwitchTimer_Tick(object sender, EventArgs e)
        {
            currentMokaAdIndex++;
            currentMokaAdIndex = currentMokaAdIndex % totalMokaAdCount;
            switchMokaAdImage();
        }

        void StoryboardTimesup_Completed(object sender, EventArgs e)
        {
            //游戏结束，跳转到完成页面
            this.gameCanvas.EndGame();
            gameSecondTimer.Stop();
            toolGenTimer.Stop();

            //跳转到结束页面
            StageManager.Instance.LastestGameScore = currentScore;
            this.NavigationService.Navigate(new Uri("/Pages/CompletePage.xaml", UriKind.RelativeOrAbsolute));
        }

        void StoryboardGO_Completed(object sender, EventArgs e)
        {
            this.gameCanvas.IsHitTestVisible = true;
            gameSecondTimer.Start();
            toolGenTimer.Start();
            gameStatus = 1;
        }

        void toolGenTimer_Tick(object sender, EventArgs e)
        {
            if (gameStatus == 1)
            {
                if (isUseColor && gameTotleSeconds % 10 == 0)
                {
                    if (r.Next(100) < 80)
                    {
                        //增加一个色盘控件
                        AddNewTool(3);
                    }
                }
                if (isUseTimer && gameTotleSeconds % 7 == 0)
                {
                    if (r.Next(100) < 90)
                    {
                        //时钟
                        AddNewTool(2);
                    }
                }
                if (isUseBomb && gameTotleSeconds % 6 == 0)
                {
                    //增加一个时钟控件
                    AddNewTool(1);

                }
                gameTotleSeconds++;
            }
        }

        /// <summary>
        /// 新增一个道具到界面上
        /// </summary>
        /// <param name="p"></param>
        private void AddNewTool(int toolType)
        {
            gameCanvas.AddToolToMap(toolType);
        }

        void gameSecondTimer_Tick(object sender, EventArgs e)
        {
            if (gameStatus == 1)
            {
                //游戏倒计时器
                leftSeconds--;
                this.timeProgress.SetLeftSecond(leftSeconds);
                if (leftSeconds == 0)
                {
                    //游戏时间到
                    gameSecondTimer.Stop();
                    toolGenTimer.Stop();
                    gameStatus = 3;
                    //显示TimesUp
                    this.StoryboardTimesup.Begin();
                    this.StoryboardHideGameCanvas.Begin();
                    //canvas不能点击
                    this.gameCanvas.IsHitTestVisible = false;
                    SoundManager.StopFireEnv();
                }

                //火焰模式相关代码
                if (IsFireMode)
                {
                    FireModeSecondCount++;
                    if (FireModeSecondCount >= 5)
                    {
                        IsFireMode = false;
                        //清空Combo
                        gameCanvas.ResetCombo();
                        this.gridFire.Visibility = System.Windows.Visibility.Collapsed;
                        this.StoryboardFire.Stop();

                        SoundManager.StopFireEnv();
                    }
                }
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //base.OnBackKeyPress(e);
            if (gameStatus == 1)
            {
                ShowPasue();
                gameStatus = 2;
            }
            else if (gameStatus == 2)
            {
                HidePause();
                gameStatus = 1;
            }
            e.Cancel = true;
        }

        private void HidePause(bool needStartTimer = true)
        {
            this.StoryboardHidePause.Begin();
            if (needStartTimer)
            {
                this.StoryboardShowGameCanvasWithPaused.Begin();
                gameSecondTimer.Start();
                toolGenTimer.Start();
            }
            this.btnPause.Visibility = System.Windows.Visibility.Visible;
        }

        private void ShowPasue()
        {
            this.StoryboardShowPause.Begin();
            this.StoryboardHideGameCanvas.Begin();
            gameSecondTimer.Stop();
            toolGenTimer.Stop();
            this.btnPause.Visibility = System.Windows.Visibility.Collapsed;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (gameStatus == 0)
            {
                StartGame();
            }
            else if (gameStatus == 1)
            {
                //继续游戏
                gameSecondTimer.Start();
                toolGenTimer.Start();
            }
            else if (gameStatus == 3)
            {
                //跳转到结束页面
                StageManager.Instance.LastestGameScore = currentScore;
                this.NavigationService.Navigate(new Uri("/Pages/CompletePage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            if (gameStatus == 1)
            {
                gameStatus = 2;
                //暂停游戏计时器
                //gameSecondTimer.Stop();
                //toolGenTimer.Stop();
                ShowPasue();
            }

        }


        /// <summary>
        /// 开始游戏
        /// </summary>
        private void StartGame()
        {
            SoundManager.StopFireEnv();
            IsFireMode = false;

            leftSeconds = 60;
            diamondCompleteCount = 0;
            currentScore = 0;
            timeProgress.SetLeftSecond(leftSeconds);
            diamondProgress.SetProgress(diamondCompleteCount, diamondCompleteBase);
            ScoreView.SetScore(currentScore);

            //使用道具
            isUseBomb = false;
            isUseColor = false;
            isUseTimer = false;
            totalToolCountInRound = 0;
            gameTotleSeconds = 1;
            if (StageManager.Instance.BombCount > 0)
            {
                StageManager.Instance.BombCount--;
                isUseBomb = true;
                totalToolCountInRound++;
            }
            if (StageManager.Instance.ColorCount > 0)
            {
                StageManager.Instance.ColorCount--;
                isUseColor = true;
                totalToolCountInRound++;
            }
            if (StageManager.Instance.TimeCount > 0)
            {
                StageManager.Instance.TimeCount--;
                isUseTimer = true;
                totalToolCountInRound++;
            }

            DispatcherTimer tempTimer = new DispatcherTimer();
            tempTimer.Interval = TimeSpan.FromMilliseconds(1200);
            tempTimer.Tick += (object sender, EventArgs e) =>
            {
                this.txtLoading.Visibility = System.Windows.Visibility.Collapsed;

                this.gameCanvas.StartNewGame();
                tempTimer.Stop();
                SoundManager.PlayEffect(SoundManager.readyGo);
                this.StoryboardGO.Begin();
                this.StoryboardShowGameCanvas.Begin();


            };
            tempTimer.Start();
        }

        /// <summary>
        /// 消除钻石，进行记分等操作
        /// </summary>
        /// <param name="count"></param>
        /// <param name="combo"></param>
        public void EliminateDiamond(int count, int combo, bool isSuperDiamond)
        {
            //记分
            int score = ScoreHelper.CalcScore(count, combo);
            currentScore += score;
            this.ScoreView.SetScore(currentScore);

            //宝石计数
            if (!isSuperDiamond)
            {
                diamondCompleteCount += count;
                if (diamondCompleteCount >= diamondCompleteBase)
                {
                    //TODO lc 生成一个宝石，调用GameCanvas
                    gameCanvas.AddNewSuperDiamond();
                    diamondCompleteCount = diamondCompleteCount % diamondCompleteBase;
                }
                diamondProgress.SetProgress(diamondCompleteCount, diamondCompleteBase);
            }

            this.txtComboTest.Text = combo.ToString();
        }

        public void ErrorEliminate()
        {
            diamondCompleteCount -= 5;
            if (diamondCompleteCount < 0)
            {
                diamondCompleteCount = 0;
            }
            diamondProgress.SetProgress(diamondCompleteCount, diamondCompleteBase);
        }

        private void btnResume_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (gameStatus == 2)
            {
                SoundManager.PlayEffect(SoundManager.clickButton);
                HidePause();
                gameStatus = 1;
            }
        }

        private void btnRestart_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (gameStatus == 2)
            {
                SoundManager.StopFireEnv();
                SoundManager.PlayEffect(SoundManager.clickButton);
                HidePause(false);
                //重新开始游戏
                IsFireMode = false;
                this.gameCanvas.RestartGame();
                //动画here
                this.StoryboardGO.Begin();
                this.StoryboardShowGameCanvas.Begin();
                SoundManager.PlayEffect(SoundManager.readyGo);

                leftSeconds = 60;
                diamondCompleteCount = 0;
                currentScore = 0;

                timeProgress.SetLeftSecond(leftSeconds);
                diamondProgress.SetProgress(diamondCompleteCount, diamondCompleteBase);
                ScoreView.SetScore(currentScore);

                isUseBomb = false;
                isUseColor = false;
                isUseTimer = false;
                totalToolCountInRound = 0;
                gameTotleSeconds = 1;

                //使用道具
                if (StageManager.Instance.BombCount > 0)
                {
                    StageManager.Instance.BombCount--;
                    isUseBomb = true;
                    totalToolCountInRound++;

                    //启动定时器
                }
                if (StageManager.Instance.ColorCount > 0)
                {
                    StageManager.Instance.ColorCount--;
                    isUseColor = true;
                    totalToolCountInRound++;
                }
                if (StageManager.Instance.TimeCount > 0)
                {
                    StageManager.Instance.TimeCount--;
                    isUseTimer = true;
                    totalToolCountInRound++;
                }
            }
        }

        private void btnMenu_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.StopFireEnv();
            //返回主菜单
            SoundManager.PlayEffect(SoundManager.clickButton);
            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void btnPause_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.clickButton);
            //暂停按钮
            if (gameStatus == 1)
            {
                ShowPasue();
                gameStatus = 2;
            }
        }

        internal void AddTime()
        {
            this.StoryboardShowAddTime.Begin();
            this.leftSeconds += 2;
            this.timeProgress.SetLeftSecond(leftSeconds);
            SoundManager.PlayEffect(SoundManager.addTime);
        }

        /// <summary>
        /// 是否是火焰模式
        /// </summary>
        public bool IsFireMode = false;
        private int FireModeSecondCount = 0;

        internal void ToFireMode()
        {
            SoundManager.PlayFireEnv();
            FireModeSecondCount = 0;
            this.gridFire.Visibility = System.Windows.Visibility.Visible;
            this.StoryboardFire.RepeatBehavior = RepeatBehavior.Forever;
            this.StoryboardFire.Begin();
            IsFireMode = true;

        }

        private void imgBanner_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            if (currentMokaAdIndex == 0)
            {
                //跳转到魔卡幻想
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=c035da4065183dbec79ffbe43fa11301ac619c2b8fdd723b692ae4b7915b3ce7", UriKind.Absolute);
            }
            else if (currentMokaAdIndex == 1)
            {
                //跳转到四国传奇
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=c8ffe9a587", UriKind.Absolute);
            }
            else if (currentMokaAdIndex == 2)
            {
                //跳转到千魔斩
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=5fc22bb64e05cb93477f153d9d61cb409179c3036db5ba85446dde582ec3c345", UriKind.Absolute);
            }
            webBrowserTask.Show();
        }

    }
}